<template>
    <form class="login-form" @submit="formSubmit">
        <!-- 手机号输入 -->
        <view class="form-item">
            <input
                class="form-input"
                v-model="formData.phone"
                placeholder="请输入手机号"
                @blur="validatePhone"
            />
            <text class="error-text" v-if="errors.phone">{{
                errors.phone
            }}</text>
        </view>

        <!-- 密码输入 -->
        <view class="form-item">
            <input
                class="form-input"
                v-model="formData.password"
                password
                placeholder="请输入密码"
                @blur="validatePassword"
            />
            <text class="error-text" v-if="errors.password">{{
                errors.password
            }}</text>
        </view>

        <!-- 操作按钮 -->
        <view class="form-actions">
            <button class="submit-btn" form-type="submit">登录</button>
            <button
                class="switch-btn"
                @click="$emit('switch-form', 'register')"
            >
                注册
            </button>
        </view>

        <!-- 忘记密码 -->
        <view class="forget-password">
            <text class="link" @click="$emit('switch-form', 'forget')"
                >忘记密码</text
            >
        </view>

        <!-- 协议勾选 -->
        <view class="agreement">
            <label class="checkbox-container">
                <checkbox
                    class="agreement-checkbox"
                    :checked="formData.agreement"
                    @click="toggleAgreement"
                />
                <text class="agreement-text">
                    登录/注册表示您同意
                    <text class="link" @click="openAgreement('user')"
                        >《用户协议》</text
                    >
                    和
                    <text class="link" @click="openAgreement('privacy')"
                        >《隐私政策》</text
                    >
                </text>
            </label>
            <text class="error-text" v-if="errors.agreement">{{
                errors.agreement
            }}</text>
        </view>
    </form>
</template>

<script setup>
import { reactive } from 'vue';
import { useLoginStore } from '../../../stores/loginStores';
import { useUserStore } from '../../../stores/userStores';

const loginStore = useLoginStore();
const userStore = useUserStore();

// 表单数据
const formData = reactive({
    phone: '',
    password: '',
    agreement: true
});

// 错误信息
const errors = reactive({
    phone: '',
    password: '',
    agreement: ''
});

// 验证规则
const validateRules = {
    phone: (value) => {
        const phoneReg = /^1[3-9]\d{9}$/;
        if (!value) return '请输入手机号';
        if (!phoneReg.test(value)) {
            return '请输入有效的手机号';
        }
        return '';
    },
    password: (value) => {
        if (!value) return '请输入密码';
        if (value.length < 6 || value.length > 20) {
            return '密码长度需为6-20位';
        }
        return '';
    },
    agreement: (value) => {
        if (!value) return '请同意用户协议和隐私政策';
        return '';
    }
};

// 字段验证方法
const validatePhone = () => {
    errors.phone = validateRules.phone(formData.phone);
};
const validatePassword = () => {
    errors.password = validateRules.password(formData.password);
};
const validateAgreement = () => {
    errors.agreement = validateRules.agreement(formData.agreement);
};

// 切换协议状态
const toggleAgreement = () => {
    formData.agreement = !formData.agreement;
    validateAgreement();
};

// 表单提交
const formSubmit = (e) => {
    // 执行所有验证
    validatePhone();
    validatePassword();
    validateAgreement();

    // 检查是否有错误
    const hasErrors = Object.values(errors).some((msg) => msg !== '');

    if (!hasErrors) {
        // console.log('表单数据:', formData);

        loginStore
            .userLogin({
                phone: formData.phone,
                password: formData.password
            })
            .then(async (res) => {
                if (res.data.code === 20000) {
                    const userData = res.data.data;
                    // console.log('用户数据：', userData);

                    // 存储用户基础信息
                    userStore.setCurrentBaseUserInfo({
                        token: userData.token,
                        userId: userData.userId
                    });

                    // 调用完整信息
                    await userStore.fetchCurrentFullUserInfo();

                    uni.reLaunch({
                        url: '/pages/home/home'
                    });
                } else {
                    uni.showToast({
                        title: res.data.message,
                        icon: 'none'
                    });
                }
            })
            .catch((error) => {
                console.error('登录请求失败:', error);

                let errorMessage = '登录失败，请重试';
                if (error.code === 'ERR_NETWORK') {
                    errorMessage = '服务器连接失败！请稍后重试！';
                } else if (error.response) {
                    // 处理 HTTP 错误响应
                    errorMessage =
                        error.response.data.message ||
                        `服务器错误: ${error.response.status}`;
                }

                uni.showToast({
                    title: errorMessage,
                    icon: 'none',
                    duration: 3000
                });
            });
    } else {
        return false;
    }
};

// 切换表单类型
const switchForm = () => {
    uni.$emit('switch-form', 'register');
    uni.$emit('switch-form', 'forget');
};

// 打开协议
const openAgreement = (type) => {
    console.log(`打开${type === 'user' ? '用户协议' : '隐私政策'}`);
};
</script>

<style lang="scss" scoped>
@import 'commonForm.scss';
</style>
